<?php

session_start();

require_once '../common/conn.php';
require_once '../common/function.php';


$dbc = new DBC();

echo "total_amount=" . $_SESSION['totalAmount'];

$sql = "SELECT * FROM AccountMoney WHERE AccUnique = " . $_SESSION['AccUnique'];

$data = $dbc->fetchData($sql);

if (isArrayNotEmpty($data) && $data[0]['Balance'] < $_SESSION['totalAmount']) {
    echo "<script type='text/javascript'>alert('余额不足')</script>";
} else {

    $sqls = array();

    $sql = "UPDATE AccountMoney SET Balance = Balance - " . $_SESSION['totalAmount'] . " WHERE AccUnique = " . $_SESSION['AccUnique'];
    array_push($sqls, $sql);

    $itemCartArray = $_SESSION['cartReady'];


    $unionNo = date("YmdHis") . "_" . $_SESSION['AccUnique'];

    for ($i = 0; $i < count($itemCartArray); $i++) {
        $idx = $itemCartArray[$i]['id_x'];
        $itemNo = $itemCartArray[$i]['ItemNo'];
        $num = $itemCartArray[$i]['num'];
        $sql = "INSERT INTO AccountMoneyDetail(AccUnique,ItemIdx,ItemCount,UpdateTime,ItemNo,UnionNo) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $idx . "','" . $num . "',getDate(),'" . $itemNo . "','" . $unionNo . "')";
        array_push($sqls, $sql);

//    $sql = "SELECT MAX(id_x)+1 AS new_id FROM item_buy_info";
//
//    $new_id = $dbc->fetchData($sql)[0]['new_id'];

        $sql = "INSERT INTO item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) "
                . "VALUES('" . $_SESSION['AccUnique'] . "','" . $_SESSION['AccountID'] . "','139','"
                . $itemNo . "','" . $num . "',3,getDate())";
        array_push($sqls, $sql);
    }


    $result = $dbc->executeBatch($sqls);

    $dbc->close();

    if ($result) {
        unset($_SESSION['cart']); //购买成功清空购物车
        unset($_SESSION['cartReady']); //购买成功清空购物车
        echo "<script type='text/javascript'>alert('购买成功')</script>";
    } else {
        echo "<script type='text/javascript'>alert('购买失败，请重试')</script>";
    }
}

echo "<script type='text/javascript'>location.href='../index.php'</script>";

